package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.OrderDB;
import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.entity.OrderDetail;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.Executors;

public class DownloadOrderTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "DownloadOrderTask";
    Set<String> orderIds = new HashSet<>();
    List<FindOrderDetail> list = new ArrayList<>();
    List<OrderDetail> readerArr = new ArrayList<>();

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取所有订单列表
            //getAllOrder();
            getAllLocalOrder();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void getAllLocalOrder() {
        File file = new File(FileUtil.getDataPath(App.mContext) + "/tbl_productorder.csv");
        list = readProductOrderCsv(file.getAbsolutePath());
        CommUtil.d(App.mContext,TAG, "tbl_productorder:" + list.size());
        orderIds.clear();
        for (FindOrderDetail detail : list) {
            orderIds.add(detail.getOrderId());
        }

        File file1 = new File(FileUtil.getDataPath(App.mContext) + "/tbl_orderdetail.csv");
        List<OrderDetail> list1 = readOrderDetailCsv(file1.getAbsolutePath());

        CommUtil.d(App.mContext,TAG, "tbl_orderdetail:" + list1.size());

        for(FindOrderDetail order : list){
            readerArr.clear();
            for(OrderDetail detail: list1){
                if(order.getOrderId().equals(detail.getOrderId())){
                    readerArr.add(detail);
                }
            }
            if(readerArr.size() > 0){
                JSONArray array = new JSONArray();
                array.clear();
                array.addAll(readerArr);
                order.setOrderDetailList(array.toString());
            }
        }

        OrderDB customerDB = new OrderDB();
        customerDB.addAllOrder(list);
    }

    public List<FindOrderDetail> readProductOrderCsv(String path) {
        List<FindOrderDetail> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(path);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String[] lines = in.nextLine().split(",");
                if (Utils.replaceStr(lines[5]).equals(SharedPreference.getPreferString("id"))) {
                    FindOrderDetail bean = new FindOrderDetail(Utils.replaceStr(lines[1]), Utils.replaceStr(lines[2]), Utils.replaceStr(lines[3]), Utils.replaceStr(lines[22]),
                            Utils.replaceStr(lines[23]), Utils.replaceStr(lines[6]), "", Utils.replaceStr(lines[4]), Utils.replaceStr(lines[5]), Utils.replaceStr(lines[8]), Utils.replaceStr(lines[9]), Utils.replaceStr(lines[10]),
                            Utils.replaceStr(lines[11]), Utils.replaceStr(lines[12]), Utils.replaceStr(lines[13]), Utils.replaceStr(lines[14]), Utils.replaceStr(lines[15]), "", Utils.replaceStr(lines[16]), Utils.replaceStr(lines[25]),
                            Utils.replaceStr(lines[17]), Long.valueOf(Utils.replaceStr(lines[28])), "", Utils.replaceStr(lines[31]), Utils.replaceStr(lines[7]));
                    readerArr.add(bean);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }

    public List<OrderDetail> readOrderDetailCsv(String path) {
        List<OrderDetail> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(path);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String[] lines = in.nextLine().split(",");
                for(FindOrderDetail order : list){
                    if(order.getOrderId().equals(Utils.replaceStr(lines[2]))){
                        OrderDetail bean = new OrderDetail(Utils.replaceStr(lines[1]), Utils.replaceStr(lines[2]), Utils.replaceStr(lines[3]), Utils.replaceStr(lines[4]),
                                Utils.replaceStr(lines[5]), Utils.replaceStr(lines[6]), Utils.replaceStr(lines[7]), Utils.replaceStr(lines[8]), Utils.replaceStr(lines[10]), Utils.replaceStr(lines[11]), Utils.replaceStr(lines[12]),
                                Utils.replaceStr(lines[13]), Utils.replaceStr(lines[14]), Utils.replaceStr(lines[19]), Long.valueOf(0));
                        readerArr.add(bean);
                    }
                }
            }
        } catch (Exception e ) {
            e.printStackTrace();
        }
        return readerArr;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllOrder() {
        try {
            String url = NetUtils.FIND_ALL_ORDER;
            long time = 0;
            if (SharedPreference.getPreferInteger("isFirstLogin") == 1) {
                time = new OrderDB().getMaxModifyTime();
            }
            String path = url + SharedPreference.getPreferString("dealer") + "&employerId=" + SharedPreference.getPreferString("id")
                    + "&userId=" + SharedPreference.getPreferString("id") + "&modifyTime=" + time;
            Log.d(TAG, "ORDER_ALL:path " + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "ORDER_ALL:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            JSONObject data = jsonObejct.getJSONObject("data");
                            List<FindOrderDetail> temList = JSONArray.parseArray(data.getJSONArray("rows").toString(), FindOrderDetail.class);
                            //将订单结果更新
                            OrderDB customerDB = new OrderDB();
                            //customerDB.addAllOrder(temList);
                            if (SharedPreference.getPreferInteger("isFirstLogin") == 0) {
                                customerDB.addAllOrder(temList);
                            } else {
                                //temList = customerDB.findAllPageOrder(1, 20, 1);
                                customerDB.updateAllOrder(temList);
                            }

                        } else {
                            if (!new OrderDB().hasData()) {
                                DownloadOrderTask product7 = new DownloadOrderTask();
                                product7.executeOnExecutor(Executors.newCachedThreadPool());
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
